package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.config.RabbitMQConfig;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillMessage;
import com.hmdp.entity.User;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class SeckillOrderConsumer {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IVoucherOrderService voucherOrderService;

    @RabbitListener(queues = RabbitMQConfig.SECKILL_QUEUE)
    public void handleSeckillMessage(SeckillMessage message) {
        UserDTO user = message.getUser();
        Long voucherId = message.getVoucherId();

        // 创建锁对象，使用用户ID作为锁标识
        RLock lock = redissonClient.getLock("lock:order:" + user.getId());

        // 获取锁
        boolean isLocked = false;
        try {
            isLocked = lock.tryLock(1, 10, TimeUnit.SECONDS);
            if (!isLocked) {
                // 获取锁失败，可能是重复下单，记录日志
                log.error("用户{}重复下单， voucherId:{}", user.getId(), voucherId);
                return;
            }

            // 执行创建订单的逻辑
            createVoucherOrder(user, voucherId);
        } catch (Exception e) {
            log.error("处理秒杀订单异常", e);
        } finally {
            // 释放锁
            if (isLocked) {
                lock.unlock();
            }
        }
    }

    @Transactional
    public void createVoucherOrder(UserDTO user, Long voucherId) {
        // 再次检查是否已经下单，防止重复下单
        LambdaQueryWrapper<VoucherOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VoucherOrder::getUserId, user.getId())
                .eq(VoucherOrder::getVoucherId, voucherId);

      //查询用户是否已经购买过该优惠券
        int count = (int) voucherOrderService.count(queryWrapper);
        if (count > 0) {
            log.error("用户{}已经购买过该优惠券， voucherId:{}", user.getId(), voucherId);
            return;
        }

        // 扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();

        if (!success) {
            log.error("优惠券{}库存不足", voucherId);
            return;
        }

        // 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(user.getId());
        voucherOrder.setVoucherId(voucherId);

        voucherOrderService.save(voucherOrder);

        log.info("用户{}创建订单成功，订单ID:{}", user.getId(), orderId);
    }
}